package com.itany.shop.dao.impl;

import com.itany.shop.dao.UserDao;
import com.itany.shop.entity.User;
import com.itany.shop.factory.ObjectFactory;
import com.itany.shop.rowmapper.UserRowMapper;
import com.itany.shop.util.JDBCTemplate;

import java.util.List;

/**
 * @author 黄衡熙
 * @version 1.0
 */
public class UserDaoImpl implements UserDao {
    private JDBCTemplate jdbcTemplate = (JDBCTemplate) ObjectFactory.getObject("jdbc");
    @Override
    public void insertUser(User user) {
        String sql = new StringBuffer()
                .append(" insert into ")
                .append(" t_user(username,password,phone,address)")
                .append(" values(?,?,?,?)")
                .toString();
        jdbcTemplate.update(sql, user.getUsername(), user.getPassword(), user.getPhone(), user.getAddress());
    }
    @Override
    public User selectByUsername(String username) {
        String sql = new StringBuffer()
                .append(" select id,username,password,phone,address ")
                .append(" from t_user ")
                .append(" where username = ? ")
                .toString();
        List<User> users = jdbcTemplate.query(sql, new UserRowMapper(), username);
        // 判断集合是否为空?
        // 如果为空则返回null,说明没有查询到数据
        // 如果不为空,此时返回的值有且仅有一条,一定是在集合的第一条数据
        return users.isEmpty() ? null : users.get(0);
    }
    @Override
    public User selectByUsernameAndPassword(String username, String password) {
        String sql = new StringBuffer()
                .append(" select id,username,password,phone,address ")
                .append(" from t_user ")
                .append(" where username = ? ")
                .append(" and password = ?")
                .toString();
        List<User> users = jdbcTemplate.query(sql, new UserRowMapper(), username, password);
        return users.isEmpty() ? null : users.get(0);
    }

    @Override
    public void updatePasswordById(Integer id, String password) {
        String sql = new StringBuffer()
                .append(" update t_user ")
                .append(" set password = ? ")
                .append(" where id = ? ")
                .toString();
        jdbcTemplate.update(sql, password, id);
    }

}
